package admin

import (
	"gitee.com/zjlsliupei/ghelp"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"go-web/models"
	"net/http"
)

// Index 首页
func Index(c *gin.Context) {
	s := sessions.Default(c)
	uid := s.Get("uid").(uint)
	menu := models.GetMenuByUid(uid)
	params := models.GetParam("title", "foot_text")
	title := ""
	if v, ok := params["title"]; ok {
		title = v.Value
	}
	footText := ""
	if v, ok := params["foot_text"]; ok {
		footText = v.Value
	}
	var defaultOpenParentId uint = 0
	if len(menu) > 0 {
		defaultOpenParentId = menu[0].ID
	}
	c.HTML(http.StatusOK, "index.html", gin.H{
		"title":               title,
		"leftMenu":            menu,
		"footText":            footText,
		"nickname":            s.Get("nickname"),
		"defaultOpenParentId": defaultOpenParentId,
	})
}

// Login 用户登录页面
func Login(c *gin.Context) {
	params := models.GetParam("title")
	title := ""
	if v, ok := params["title"]; ok {
		title = v.Value
	}
	s := sessions.Default(c)
	loginErrMsg := s.Get("loginErrMsg")
	s.Delete("loginErrMsg")
	s.Save()

	c.HTML(http.StatusOK, "login.html", gin.H{
		"title":       title,
		"loginErrMsg": loginErrMsg,
	})
}

// LoginPost 用户执行登录
func LoginPost(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	user := models.GetUserByUsername(username)
	if user.ID <= 0 {
		s := sessions.Default(c)
		s.Set("loginErrMsg", "用户不存在")
		s.Save()
		c.Redirect(http.StatusFound, "/admin/login")
		return
	}
	if ghelp.Md5(password) != user.Password {
		s := sessions.Default(c)
		s.Set("loginErrMsg", "用户名密码不正确")
		s.Save()
		c.Redirect(http.StatusFound, "/admin/login")
		return
	}

	s := sessions.Default(c)
	s.Set("uid", user.ID)
	s.Set("nickname", user.Nickname)
	s.Options(sessions.Options{
		MaxAge: 30 * 60,
	})
	s.Save()
	c.Redirect(http.StatusFound, "/admin/index")
}

// LoginOut 退出登录
func LoginOut(c *gin.Context) {
	s := sessions.Default(c)
	s.Clear()
	s.Save()
	c.Redirect(http.StatusFound, "/admin/login")
}
